using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.InteropServices;

namespace AssetCapture
{
    public partial class AssetLoginForm : Form
    {
        string m_ConnectionString;
        public delegate void UserLogin(int ID);
        UserLogin reportID;
        Base pipeServer;

        private const int WM_SCROLL = 276; // Horizontal scroll
        private const int WM_VSCROLL = 277; // Vertical scroll
        private const int SB_LINEUP = 0; // Scrolls one line up
        private const int SB_LINELEFT = 0;// Scrolls one cell left
        private const int SB_LINEDOWN = 1; // Scrolls one line down
        private const int SB_LINERIGHT = 1;// Scrolls one cell right
        private const int SB_PAGEUP = 2; // Scrolls one page up
        private const int SB_PAGELEFT = 2;// Scrolls one page left
        private const int SB_PAGEDOWN = 3; // Scrolls one page down
        private const int SB_PAGERIGTH = 3; // Scrolls one page right
        private const int SB_PAGETOP = 6; // Scrolls to the upper left
        private const int SB_LEFT = 6; // Scrolls to the left
        private const int SB_PAGEBOTTOM = 7; // Scrolls to the upper right
        private const int SB_RIGHT = 7; // Scrolls to the right
        private const int SB_ENDSCROLL = 8; // Ends scroll
        
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
        /// <summary>
        /// The Main Function for Asset loginForm
        /// </summary>
        /// <param name="sqlConnection"></param>
        /// <param name="report"></param>
        public AssetLoginForm(string sqlConnection, UserLogin report)
        {
            InitializeComponent();
            m_ConnectionString = sqlConnection;
            reportID = report;

            pipeServer = new Base();

            pipeServer.MessageReceived += new Base.MessageReceivedHandler(pipeServer_MessageReceived);

            if (!pipeServer.Running)
            {
                pipeServer.PipeName = @"\\.\pipe\Asset\";
                pipeServer.Start();
            }

            CheckMedia();

            infoTimer.Start();
            infoTimer.Tick += new EventHandler(infoTimer_Tick);

            StatusSaving.Start();
            StatusSaving.Tick += new EventHandler(StatusSaving_Tick);
        }

        void StatusSaving_Tick(object sender, EventArgs e)
        {
            StreamWriter sW = new StreamWriter(Application.StartupPath + "\\IngestionLog.txt", true);
            sW.WriteLine(Tbox_Status.Text);
            Tbox_Status.Text = "";
            sW.Close();
        }

        void pipeServer_MessageReceived(Base.Client client, string message)
        {
            this.Invoke(new Base.MessageReceivedHandler(updateActivity), new object[] { client, message });
        }

        void updateActivity(Base.Client client, string message)
        {
            Tbox_Status.Text += DateTime.Now+ ":" +  message + "\r\n";
            SendMessage(Tbox_Status.Handle, WM_VSCROLL, (IntPtr)SB_ENDSCROLL, IntPtr.Zero);

            if (message == "Auto Ingest Restart")
            {
                AssetFunction restartAsset = new AssetFunction();
                restartAsset.autoProcess();
            }
        }

        //Display the proper feedback for user 
        void infoTimer_Tick(object sender, EventArgs e)
        {
            CheckMedia();
        }

        //Display the Information related to the Ingestion and Distribution
        private void CheckMedia()
        {
            string command = "select value from GlobalConfig where Property = 'FTPBatchIngestPath'";
            string pathFTP = getDataObject(command).ToString();

            DirectoryInfo dir = new DirectoryInfo(pathFTP);
            int fileCount = dir.GetFiles().Length;
            int totalCount = dir.GetDirectories().Length - 2 + fileCount;

            command = "select Count(ID) from Media where ThumbnailVidPath is null";
            int thumbNailCount = Convert.ToInt32(getDataObject(command)) - 1;

            command = "select Count(ID) from Mediainstance where FullyPresentNN = 'false' and FullyPresentBackupNN = 'false' and MediaID is not null";
            int mediaMissingCount = Convert.ToInt32(getDataObject(command));

            Label_AutoIngest.Text = "Batch Ingesting : " + totalCount;
            Label_AutoThumbnail.Text = "Thumbnail Generating : " + thumbNailCount;
            Label_MediaMissing.Text = "Distributing Media : " + mediaMissingCount;
        }

        private void TBox_UserName_Click(object sender, EventArgs e)
        {
            TBox_UserName.SelectAll();
        }

        /// <summary>
        /// Login Button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Login_Click(object sender, EventArgs e)
        {
            string command = "sproc_WEB_AuthenticateUser @UserName='" + TBox_UserName.Text + "', @Password='" + TBox_Password.Text + "'";

            int ID = Convert.ToInt32(getDataObject(command));

            if (ID == 0)
                MessageBox.Show("Log In Fail");
            else
            {
                reportID(ID);
                TBox_UserName.Text = "User Name";
                TBox_Password.Text = "";
                this.Hide();
            }
        }

        //Get the SQL command and return single object item using DataReader to speed up the communication
        public object getDataObject(string selectSQL)
        {
            SqlConnection con = new SqlConnection(m_ConnectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataReader reader = null;
            object ob = new object();

            try
            {
                con.Open();
                reader = cmd.ExecuteReader();
                reader.Read();
                if (reader.HasRows)
                    ob = reader[0];//Only read ONE data in the first of list
                else
                    ob = 0;
                reader.Close();

            }
            catch (Exception err)
            {
                //MessageBox.Show("Error occur while connect to DataBase via DataReader, Check Connection : \n" + err);
            }
            finally
            {
                con.Close();
            }
            return ob;

        }

        private void TBox_Password_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Btn_Login_Click(sender, e);
            }
        }

        private void Btn_SaveStatus_Click(object sender, EventArgs e)
        {
            StreamWriter sW = new StreamWriter(Application.StartupPath + "\\IngestionLog.txt", true);
            sW.WriteLine(Tbox_Status.Text);
            sW.Close();
        }

        private void Btn_Clear_Click(object sender, EventArgs e)
        {
            Tbox_Status.Text = "";
        }

    }
}